<?php
class omeanalysts_mdl_ome_orderdeliverycomp extends dbeav_model{

    //var $has_export_cnf = true;

    var $export_name = '发货核对表';

    public function table_name($real=false){
        $table_name = 'ome_delivery';
        if($real){
            return kernel::database()->prefix.$table_name;
        }else{
            return $table_name;
        }
    }

    public function count($filter=null){
         
        $where = $this->_filter($filter); 

        
        $rows=$this->getDeliveryInfo($where,$limit,$offset);

        return count($rows);
    } 
    function getdividefeenew($order_id,$bn)
    {
      $sql="SELECT  items.bn,sum(items.divide_order_fee) divide_order_fee,sum(items.nums) nums from sdb_ome_orders os 
              inner join sdb_ome_order_items items on os.order_id=items.order_id
              where os.order_id='$order_id' and items.bn='$bn' and items.delete='false' 
              group by items.bn ";
      $rows = $this->db->select($sql);
      return $rows;
    }
    //add by ldward 发货完成过数核对表
    function getDeliveryInfo($where,$limit,$offset) 
    {
        $sql = "SELECT odo.order_id,d.* , axshipno ,axorderno,dnl.status as dnl_status
                FROM sdb_wms_deliverycomp a
                LEFT JOIN sdb_wms_deliverycomp_line dcl on (a.id = dcl.deliverycomp_id)
                LEFT JOIN sdb_wms_deliverynote dn on (dcl.deliverynote_id = dn.id )
                LEFT JOIN sdb_wms_deliverynote_line dnl on ( dn.id = dnl.deliverynote_id )
                LEFT JOIN sdb_wms_delivery d on (dnl.delivery_id = d.delivery_id)
                LEFT JOIN sdb_ome_delivery od on (od.delivery_bn=d.outer_delivery_bn)
                LEFT JOIN sdb_ome_delivery_order odo on (odo.delivery_id=od.delivery_id)
                left join sdb_ome_shop f on d.shop_id=f.shop_id
                  where ".$where." ";
        $compdata = $this->db->select($sql);
        $deliveryItemsMdl = app::get('wms')->model('delivery_items');
        $shop_obj = app::get('ome')->model('shop');
        $sales_material = app::get('material')->model('basic_material');
        $sales_material_ext = app::get('material')->model('basic_material_ext');
        $rows = array();
        foreach ($compdata as $cv) 
        {
            $shopData = $shop_obj->getRow($cv['shop_id']);
            $shop_bn = $shopData['AXCustomer'];
            if ($shop_bn == '') 
            {
                continue;
            }
            $deliveryItemsData = $deliveryItemsMdl->getList('*', array('delivery_id' => $cv['delivery_id']));
            if (!empty($deliveryItemsData)) 
            {
                foreach ($deliveryItemsData as $v) 
                {
                    $salesMData = $sales_material->dump(array('material_bn' => $v['bn']), 'bm_id');
                    $unit = $sales_material_ext->dump(array('bm_id' => $salesMData['bm_id']), 'unit');

                    $divide_order_fee=$this->getdividefeenew($cv['order_id'],$v['bn']);
                    $SalesPrice = round(($divide_order_fee[0]['divide_order_fee']/$divide_order_fee[0]['nums']),4);
                
                    $tmp = $shop_bn .'-'.$shopData['shop_bn'].'-' . $v['bn'] . '-' . $SalesPrice . '-' . $unit['unit'] . '-' . $cv['axshipno'] . '-' . $cv['axorderno'] . '-' . $cv['carno'];
                    $salesPlatfrom = '其他';
                    if ($shopData['shop_type'] != '') {
                        $salesPlatfrom = ome_shop_type::shop_name($shopData['shop_type']);
                    }
                    if (isset($number_tmp[$tmp])) {
                        $number_tmp[$tmp] += $v['number'];
                    } else {
                        $number_tmp[$tmp] = $v['number'];
                    }
                    $rows[$tmp] = array(
                      'CustAccount' => $shop_bn,
                      'ItemId' => $v['bn'],
                      'SalesPrice' => $SalesPrice,
                      'SalesQty' => $number_tmp[$tmp],
                      'SalesUnit' => $unit['unit'],
                      'PackingSlipId' =>$cv['axshipno'],
                      'SalesId' =>$cv['axorderno'],
                      'LicencePlateNo' =>$cv['carno'],
                      'shopName' =>$shopData['shop_bn'],
                      'salesPlatfrom' =>$salesPlatfrom 
                    );
                }
            }
        }
        return $rows;
    }

    public function getlist($cols='*', $filter=array(), $offset=0, $limit=-1, $orderType=null)
    {
        if(!$filter['time_from'] && !$filter['time_to']){
            return false;
        }else{
            $where = $this->_filter($filter); 
            $rows=$this->getDeliveryInfo($where,$limit,$offset);
            return $rows;
        }   
    }
    
    public function searchOptions(){
        $parentOptions = parent::searchOptions();
        $childOptions = array(
            'order_bn'=>app::get('base')->_('订单号'),
        );
        return $Options = array_merge($parentOptions,$childOptions);
    }

    public function _filter($filter,$tableAlias=null,$baseWhere=null){


        $where = array(1);
       if(empty($filter['time_from']))
        {
          $where[]=' 1=2 ';
        }
        if(isset($filter['time_from']) && $filter['time_from']){
            $where[] = ' a.deliverycomp_time >='.strtotime($filter['time_from']);
        }
        if(isset($filter['time_to']) && $filter['time_to']){
            $where[] = ' a.deliverycomp_time <'.(strtotime($filter['time_to'])+86400);
        }
        if(isset($filter['shop_id'])   && $filter['shop_id']){
            $where[] = ' f.shop_id  =\''.addslashes($filter['shop_id']).'\'';
        }
        if(!$filter['shop_id'] && $filter['shop_ids']){
            $where[] = ' f.shop_id IN (\''.implode('\',\'', $filter['shop_ids']).'\')';
        }
        unset($filter['shop_id']);
        if(isset($filter['AXCustomer']) && $filter['AXCustomer']){
            $where[]= ' d.ax_shopname  =\''.addslashes($filter['AXCustomer']).'\'';
        }  
        if(isset($filter['axcustomercode']) && $filter['axcustomercode']){
            $where[]= ' f.AXCustomer  =\''.addslashes($filter['axcustomercode']).'\'';
        }
        if(isset($filter['deliverycomp_bn'])  && $filter['deliverycomp_bn']){
            $where[] = ' a.deliverycomp_bn =\''.addslashes($filter['deliverycomp_bn']).'\'';
        }
        if(isset($filter['p_bn']) && $filter['p_bn']){
            $where[] = ' g.bn =\''.addslashes($filter['p_bn']).'\'';
        }
        if(isset($filter['order_bn']) && $filter['order_bn']){
            $where[] = ' os.order_bn =\''.addslashes($filter['order_bn']).'\'';
        }
        if(isset($filter['axorderno']) && $filter['axorderno']){
            $where[] = ' dnl.axorderno =\''.addslashes($filter['axorderno']).'\'';
        }
          
        return implode($where,' AND ');
    }

    public function get_schema(){
        $schema = array (
            'columns' => array (
                'CustAccount' =>
                array (
                  'type' => 'varchar(255)',
                  'required' => true,
                  'label' => '客户',
                  'editable' => false,
                  'searchtype' => 'has',
                  'filtertype' => 'normal',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '120',
                ),
                'ItemId' =>
                array (
                  'type' => 'varchar(255)',
                  'label' => '物料',
                  'editable' => false,
                  'searchtype' => 'has',
                  'filtertype' => 'normal',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '120',
                ),
                'SalesPrice' =>
                array (
                  'type' => 'money',
                  'label' => '价格',
                  'editable' => false,
                  'searchtype' => 'has',
                  'filtertype' => 'normal',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '100',
                ),
                'SalesQty' =>
                array (
                  'type' => 'number',
                  'required' => true,
                  'label' => '数量',
                  'comment' => '数量',
                  'editable' => false,
                  'width' =>140,
                  'searchtype' => 'has',
                  'filtertype' => 'yes',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                ),
                'SalesUnit' =>
                array(
                    'type' => 'varchar(32)',
                    'required' => true,
                    'label' => '单位',
                    'is_title' => true,
                    'width' => 125,
                    'searchtype' => 'nequal',
                    'editable' => false,
                    'filtertype' => 'normal',
                    'filterdefault' => true,
                    'in_list' => true,
                    'default_in_list' => false,
                ),
                'PackingSlipId' =>
                array (
                  'type' => 'varchar(20)',
                  'label' => 'AX发货单号',
                  'required' => true,
                  'default' => 0,
                  'editable' => false,
                ),
                'SalesId' =>
                array (
                  'type' => 'varchar(20)',
                  'label' => 'AX订单号',
                  'required' => true,
                  'default' => 0,
                  'editable' => false,
                ),
                'LicencePlateNo' =>
                array (
                  'type' => 'varchar(32)',
                  'required' => true,
                  'label' => '车牌号',
                  'comment' => '车牌号',
                  'editable' => false,
                  'width' =>140,
                  'searchtype' => 'has',
                  'filtertype' => 'yes',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                ),
                'shopName' =>
                array (
                  'type' => 'varchar(20)',
                  'label' => '店铺编码',
                  'comment' => '店铺编码',
                  'editable' => false,
                  'in_list' => true,
                ),
                'salesPlatfrom' =>
                array (
                  'type' => 'varchar(30)',
                  'label' => '平台',
                  'editable' => false,
                  'is_title' => true,
                ),
            ),
            'idColumn' => 'name',
            'in_list' => array (
                0 => 'CustAccount',
                1 => 'ItemId',
                2 => 'SalesPrice',
                3 => 'SalesQty',
                4 => 'SalesUnit',
                5 => 'PackingSlipId',
                6 => 'SalesId',
                7 => 'LicencePlateNo',
                8 => 'shopName',
                9 => 'salesPlatfrom',
            ),
            'default_in_list' => array (
                0 => 'CustAccount',
                1 => 'ItemId',
                2 => 'SalesPrice',
                3 => 'SalesQty',
                4 => 'SalesUnit',
                5 => 'PackingSlipId',
                6 => 'SalesId',
                7 => 'LicencePlateNo',
                8 => 'shopName',
                9 => 'salesPlatfrom',   
            ),
        );
        return $schema;
    }

    /**
     * 获得日志类型(non-PHPdoc)
     * @see dbeav_model::getLogType()
     */
    public function getLogType($logParams) {
        $type = $logParams['type'];
        $logType = 'none';
        if ($type == 'export') {
            $logType = $this->exportLogType($logParams);
        }
        elseif ($type == 'import') {
            $logType = $this->importLogType($logParams);
        }
        return $logType;
    }
    /**
     * 导出日志类型
     * @param Array $logParams 日志参数
     */
    public function exportLogType($logParams) {
        $params = $logParams['params'];
        $type = 'report';
        if ($logParams['app'] == 'omeanalysts' && $logParams['ctl'] == 'ome_delivery') {
            $type .= '_purchaseReport_expressAnalysis';
        }
        $type .= '_export';
        return $type;
    }
    /**
     * 导入操作日志类型
     * @param Array $logParams 日志参数
     */
    public function importLogType($logParams) {
        $params = $logParams['params'];
        $type = 'report';
        if ($logParams['app'] == 'omeanalysts' && $logParams['ctl'] == 'ome_delivery') {
            $type .= '_purchaseReport_expressAnalysis';
        }
        $type .= '_import';
        return $type;
    }

    function io_title( $filter, $ioType='csv' )
    {
        switch( $filter ){
            case 'delivery':
                $this->oSchema['csv'][$filter] = array(
                    '*:客户' => 'CustAccount',
                    '*:物料' => 'ItemId',
                    '*:价格' => 'SalesPrice',
                    '*:数量' => 'SalesQty',
                    '*:单位' => 'SalesUnit',
                    '*:AX发货单号' => 'PackingSlipId',
                    '*:AX订单号' => 'SalesId',
                    '*:车牌号' => 'LicencePlateNo',
                    '*:店铺编码' => 'shopName',
                    '*:平台' => 'salesPlatfrom',
                );
                break;
        }
        $this->ioTitle[$ioType][$filter] = array_keys( $this->oSchema[$ioType][$filter] );
        return $this->ioTitle[$ioType][$filter];
    }

    //根据查询条件获取导出数据
    public function getExportDataByCustom($fields, $filter, $has_detail, $curr_sheet, $start, $end)
    {
          //根据选择的字段定义导出的第一行标题
          if($curr_sheet == 1){

              $title = array();
              foreach($this->io_title('delivery') as $k => $v ){
                  $title[] = mb_convert_encoding($v, 'GBK', 'UTF-8');
              }

              $data['content']['main'][0] = '"'.implode('","',$title).'"';
          }

            $where = $this->_filter($filter);
            $omedelivery=$this->getDeliveryInfo($where,$end,$start);
            foreach ($omedelivery as $k => $aFilter) {
                $exptmp_data = array();
                foreach ($aFilter as $col => $val) {
                    $aFilter[$col] = mb_convert_encoding($aFilter[$col], 'GBK', 'UTF-8');
                    $exptmp_data[] = $aFilter[$col];
                }
                $data['content']['main'][] = implode(',', $exptmp_data);
            }
            return $data;
        
    }
}
